<template>
  <div class="app-container checked">
    <div class="filter-container">
      <el-input v-model="query.query.templateName" placeholder="请输入模版名称" @keyup.enter.native="search" clearable />
      <el-select v-model="query.query.templateClassify" placeholder="请选择模版分类" clearable>
        <el-option v-for="item in templateClassifyList" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>
      <el-button type="primary" icon="el-icon-search" @click="search">{{ $t("table.search")
        }}</el-button>
      <el-button type="primary" icon="el-icon-upload2" @click="importExportVisible = true">上传</el-button>
    </div>
    <el-dialog title="合同导入" :visible.sync="importExportVisible" @closed="handleClose">
      <el-form :model="importExportForm" :rules="rules" ref="ruleForm">
        <el-row>
          <el-col :span="12">
            <el-form-item label="模版名称" prop="templateName" :label-width="formLabelWidth">
              <el-input v-model="importExportForm.templateName" placeholder="请输入模版名称" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="模版分类" prop="templateClassify" :label-width="formLabelWidth">
              <el-select style="width: 100%;" v-model="importExportForm.templateClassify" placeholder="请选择模版分类">
                <el-option v-for="item in templateClassifyList" :label="item.label" :value="item.value"
                  clearable></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="模版导入" prop="file" :label-width="formLabelWidth">
              <el-button type="text" @click="downloadExcel">下载模版</el-button>
              <el-upload class="elUpload" ref="elUpload" drag :auto-upload="false" action="#" :limit="1"
                :on-change="handleChange" :on-remove="handleRemove">
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="importExportVisible = false">取 消</el-button>
        <el-button type="primary" @click="importExportSure">确 定</el-button>
      </span>
    </el-dialog>
    <el-table :data="tableData" style="width: 100%; margin-bottom: 20px" row-key="id" highlight-current-row
      @selection-change="handleInfaceSelectionChange" border :header-cell-style="{ 'text-align': 'center' }"
      :cell-style="{ 'text-align': 'center' }">
      <!-- <el-table-column type="selection" width="55" /> -->
      <el-table-column prop="templateName" label="模版名称" sortable />
      <el-table-column prop="templateClassify" label="模版分类" sortable>
        <template slot-scope="{row:{templateClassify}}">
          {{ getType(templateClassify) }}
        </template>
      </el-table-column>
      <el-table-column width="240px" :label="$t('table.actions')" fixed="right">
        <template slot-scope="{ row, $index }">
          <div>
            <el-button type="primary" size="mini" @click="handleCLick(0, row)">{{
        $t("table.download") }}</el-button>
            <el-button type="danger" size="mini" @click="handleCLick(1, row)">{{
        $t("table.delete") }}</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total" :total="total" :page.sync="query.pageIndex" :limit.sync="query.pageSize"
      @pagination="getInfo" />
  </div>
</template>
<script>

import { templateList, templateDownload, templateDel, templateAdd } from '@/api/weeklyShipmentPlan'
import { monthExpExcel } from '@/api/productionPlan'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { deepClone, downLoadTemplate, downfile } from '@/utils'
export default {
  name: 'Productionplan',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      templateClassifyList: [{
        label: '销售合同模版',
        value: '1'
      }, {
        label: '发货单模版',
        value: '2'
      }, {
        label: '采购合同国内版模板',
        value: '3'
      }, {
        label: '采购合同国际版模板',
        value: '4'
      },{
        label: '采购收货单',
        value: '5'
      }],
      formLabelWidth: '100px',
      importExportVisible: false,
      total: 0,
      query: {
        pageSize: 10,
        pageIndex: 1,
        query: {
          templateClassify: '',
          templateName: ''
        }
      },
      tableData: [],
      rules: {
        templateName: [
          { required: true, message: '请输入模版名称', trigger: 'blur' }
        ],
        templateClassify: [
          { required: true, message: '请选择模版分类', trigger: 'change' }
        ],
        file: [
          { required: true, message: '请导入模版', trigger: 'change' }
        ]
      },
      importExportForm: {
        file: null,
        templateName:'',
        templateClassify:null
      }
    }
  },
  mounted() {
    this.getInfo()
  },
  methods: {
    getType(type){
      if(type == 1){
        return '销售合同模版'
      }else if(type == 2){
        return '发货单模版'
      }else if(type == 3){
        return '采购合同国内版模板'
      }else if(type == 4){
        return '采购合同国际版模板'
      }else if(type == 5){
        return '采购收货单'
      }
    },
    handleClose() {
      this.handleRemove()
      this.$refs['elUpload'].clearFiles()
      this.$refs['ruleForm'].resetFields()
    },
    async importExportSure() {
      this.$refs['ruleForm'].validate(async (valid) => {
        if (valid) {
          const formData = new FormData()
          for (let key in this.importExportForm) {
            formData.append(key, this.importExportForm[key])
          }
          await templateAdd(formData)
          this.getInfo()
          this.$message.success('导入成功')
          this.importExportVisible = false
        }
      })
    },
    getInfo() {
      templateList(this.query).then((res) => {
        const { records, total } = res
        this.tableData = records
        this.total = total
      })
    },
    search() {
      this.query.pageIndex = 1
      this.getInfo()
    },
    async handleCLick(val, { id,templateClassify }) {
      // 0:下载；1-删除
      if (val == 0) {
        try {
          await templateDownload(id)
        } catch (err) {
          downfile(`${this.getType(templateClassify)}.xlsx`, err)
        }
      } else {
        this.$confirm('确认删除?', '警告', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          await templateDel(id)
          this.getInfo()
          this.$message.success('删除成功')
        })
      }
    },
    downloadExcel() {
      const { templateClassify } = this.importExportForm
      if (!templateClassify) {
        this.$message.warning('请先选择模版分类')
        return
      }
      let downloadTitle;
      switch (templateClassify) {
        case "1":
          downloadTitle = '销售合同模版'
          break;
        case "2":
          downloadTitle = '发货单模版'
          break;
        case "3":
          downloadTitle = '采购合同国内版模板'
          break;
        case "4":
          downloadTitle = '采购合同国际版模版'
          break;
      }
      downLoadTemplate(`${downloadTitle}.xlsx`, `${downloadTitle}.xlsx`)
    },
    handleChange(file, fileList) {
      this.importExportForm.file = file.raw
    },
    handleRemove() {
      this.importExportForm.file = ''
    }
  },
  watch: {
    'importExportForm.file'(val) {
      if (val) this.$refs['ruleForm'].clearValidate(['file'])
    }
  },

}
</script>
